package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoimpl implements UserDao {
    @Override
    public List<User> findAll() {
            List<User> users = new ArrayList<>();
            Connection connection = null;
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        //2.获取连接(url,password,username)
        String url="jdbc:mysql://127.0.0.1:3306/stu_user?charactern=UTF-8";
        try {
           connection = DriverManager.getConnection(url, "root", "ran09105019");
       /* if (connection!=null){
            System.out.println("连接成功");
        }*/
            String sql="select * from user";

            //4.预编译sql
            PreparedStatement prepareStatement = connection.prepareStatement(sql);

            //5.有参数设置参数

            //6.执行sql
            ResultSet resultSet = prepareStatement.executeQuery();
            //7.遍历结果集
            while (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
                //添加到集合中
                users.add(user);

            }
            //返回集合
            return users;
            //8.关资源


            //把集合中的数据存储在作用域中


        } catch (SQLException e) {
            e.printStackTrace();

        }finally {

        }


        return null;
    }
}
